<?php
/**
 * DefaultController
 * 
 * @author
 * @version 
 */
require_once 'BaseController.php';
class DefaultController extends BaseController {
	
	protected $user;
	
	protected $permitted;
	
	public function checkPersistentLogin($updateCookie = false) {
		$request = $this->getRequest ();
		if ($this->_getParam('block-persistent') == 1)
			return null;
		if ($request instanceof Zend_Controller_Request_Http) {
			require_once 'models/PersistentLogin.php';
			$pl = PersistentLogin::fromCookies ( $request );
			if ($pl == null)
				return null;

			$sessionId = $request->getCookie ( 'loginSessionID' );
			if ($sessionId == null)
				return null;
			if ($pl->isSessionIDValid ( $sessionId )) {
				if ($updateCookie)	{
					//cookies are valid, create a new token
					$loginSessionID = Utils::createPL_LoginTokenID ();
					$pl->setLoginSessionID ( $loginSessionID );
					$pl->updateRow ();
				
					//issue user a new cookie
					$cookies = $pl->createCookies ();
					$this->_helper->sendCookies ( $cookies );
				}
				
				$this->SetSessionValue ( 'userAuth', 'username', $pl->getUserID () );
				return $pl->getUserID ();
			} else {
				//invalid login session id detected, theft assumed
				//FIXME: Doan code nay co loi khi user mo 2 tab cung luc
//				$this->logout ( false, false );
				
				//$this->_forward ( 'login', 'user', null, array ('init-error' => GlobalConfig::LOGIN_INIT_ERROR_THEFT ) );
			}
		}
		return null;
	}
	
	/**
	 * 
	 * Check if user has permission to perform the current action
	 */
	public function isPermitted() {
		return $this->permitted;
	}
	
	public function getUser() {
		return $this->user;
	}
	
	public function SetSessionTimeout($namespace, $timeout) {
		$auth = new Zend_Session_Namespace ( $namespace );
		$auth->setExpirationSeconds ( $timeout );
	}
	
	public function GetSessionValue($namespace, $valueName) {
		$auth = new Zend_Session_Namespace ( $namespace );
		return $auth->$valueName;
	}
	
	public function SetSessionValue($namespace, $valueName, $value) {
		$auth = new Zend_Session_Namespace ( $namespace );
		$auth->$valueName = $value;
	}
	
	public function checkUser()	{
		Zend_Auth::getInstance ()->setStorage ( new Zend_Auth_Storage_Session ( 'userAuth' ) );
		$uid = $this->GetSessionValue ( 'userAuth', 'username' );
		if ($uid == null)	{
			$uid = $this->checkPersistentLogin ($this->_getParam('update-persistent') == '1');
		}
		$this->setupUser ( $uid );
	}
	
	/**
	 * Check for user permission before processing the current action
	 * (non-PHPdoc)
	 * @see library/Zend/Controller/Zend_Controller_Action::preDispatch()
	 */
	public function preDispatch() {
		$this->checkUser();
		$this->setupUserBar ();
		$this->checkPermission ();
	}
	
	public function setupUser($uid) {
		if ($uid) {
			$user = new User ( $uid );
			//FIXME: Temporary solution
			if ($user->role == null)	{
				$this->user = null;
			} else {
			if ($user->block == 1)	{
				$this->user = null;
			} else {
				$this->user = $user;
			}
			}
		} else {
			$this->user = null;
		}
	}
	
	/**
	 * 
	 * Authorize the user
	 * @param unknown_type $throws
	 * @throws PermissionDeniedException
	 */
	public function checkPermission($throws = true) {
		$this->permitted = false;
		if ($this->getUser () != null) {
			$permit = $this->permit ( $this->getUser () );
		} else {
			$permit = $this->defaultPermission ();
		}
		if (! $permit) {
			$this->permitted = false;
			if ($throws) {
				require_once ('Exceptions/PermissionDeniedException.php');
				throw new PermissionDeniedException ();
			}
			return false;
		}
		$this->permitted = true;
		return true;
	}
	
	/**
	 * 
	 * Setup the user bar
	 */
	public function setupUserBar() {
		$user = $this->getUser ();
		if ($user != null) {
			if ($user->name) {
				$this->view->welcome_msg = Message::WELCOME . " " . $user->name;
			} else {
				$this->view->welcome_msg = Message::WELCOME . " " . $user->username;
			}
			$this->view->usr = "<a href='" . $this->view->url ( array ("controller" => "user", "action" => "logout" ) ) . "'>" . Message::LOGOUT . "</a>";
			$this->view->usercp = $this->view->render ( 'includes/user-cp-box.phtml' );
		} else {
			$req = $this->getRequest ();
			$controller = $req->getControllerName ();
			$action = $req->getActionName ();
			$this->view->welcome_msg = Message::WELCOME_PLZ_LOGIN;
			$this->view->usr = "<a href='" . $this->view->url ( array ("controller" => "user", "action" => "login", "refC" => $controller, "refA" => $action ) ) . "'>" . Message::LOGIN . "</a>";
			$this->view->usr .= "&nbsp;<span style='font-weight: bold; color: white'>|</span>&nbsp;<a href='" . $this->view->url ( array ("controller" => "user", "action" => "register") ) . "'>" . Message::REGISTER . "</a>";
		
		}
	}
	
	// permit an action or not?
	public function permit($user) {
		$controller = $this->getRequest ()->getControllerName ();
		$action = $this->getRequest ()->getActionName ();
		$permission = new Permission ( null );
		return $permission->check ( $user->role, $controller, $action );
	}
	
	public function defaultPermission() {
		$controller = $this->getRequest ()->getControllerName ();
		$action = $this->getRequest ()->getActionName ();
		$permission = new Permission ( null );
		return $permission->check ( 'default', $controller, $action );
	}
	
	/**
	 * (non-PHPdoc)
	 * @see library/Zend/Controller/Zend_Controller_Action::_redirect()
	 * @deprecated this function has been deprecated for internal use
	 * and only useful for redirecting to external url
	 */
	public function _redirect($url, $options) {
		return parent::_redirect ( $url, $options );
	}
	
	public function hasInputParam($param) {
		if (! $this->_hasParam ( $param ))
			return false;
		$p = $this->getRequest ()->getParam ( $param );
		if ($p === '')
			return false;
		return true;
	}
	
	public function userHasLogin() {
		return ($this->user != null);
	}
	
	public function destroySession() {
		Zend_Session::destroy ( true );
		$this->user = null;
	}
	
	public function sendExpiredCookies() {
		require_once 'models/PersistentLogin.php';
		//make PL cookie expired
		$cookies = PersistentLogin::createExpiredCookies ();
		$this->_helper->sendCookies ( $cookies );
	}
	
	public function deleteCookies($notCheckSessionValidation = true) {
		require_once 'models/PersistentLogin.php';
		$pl = PersistentLogin::fromCookies ( $this->getRequest () );
		if ($pl != null) {
			$sessionId = $this->getRequest ()->getCookie ( 'loginSessionID' );
			if ($notCheckSessionValidation || $pl->isSessionIDValid ( $sessionId )) {
				$pl->deleteRow ();
			}
		}
	}
	
	/**
	 * 
	 * Logout user
	 */
	public function logout($notCheckSessionValidation = true, $destroySession = true) {
		$this->SetSessionValue ( 'userAuth', "username", NULL ); // just make sure :-)
		if ($destroySession) {
			$this->destroySession ();
		}
		$this->sendExpiredCookies ();
		$this->deleteCookies ( $notCheckSessionValidation );
	}
}
